//
// Created by root on 2/22/18.
//

#include <string.h>
#include "sys.h"

#define MAX_SIZE       512

#define COMMENT_CHAR   '$'
#define STATEMENT_CHAR 's'
#define STATEMENT_STR  "statement:"
#define NAME_CHAR      'n'
#define NAME_STR       "name:"
#define FUNCTION_CHAR  'f'
#define FUNCTION_STR   "function:"
#define MAPPING_CHAR   'm'
#define MAPPING_STR    "mapping:"
#define RUN_CHAR       'r'
#define RUN_STR        "run:"
#define EVAL_CHAR      'e'
#define EVAL_STR       "eval:"

#define PAREN_L        '{'
#define PAREN_R        '}'
#define MACRO_DEF_MACRO       "defmacro"

static String get_sys_macro_string(String s, FILE *fp) {
    int c = 0;
    int i = 0;
    String macro = NULL;

    i = strlen(s);
    while (i > 0) {
        c = getc(fp);
        i--;
    }

    i = 0;
    macro = alloc_string(MAX_SIZE);
    while (c != '\n') {
        c = getc(fp);
        macro[i++] = c;
    }
    macro[--i] = '\0';

    return trim_string(macro);
}


void* parse_sys_macro(FILE* fp) {
    String source = NULL;
    Mapping *mapping = NULL;
    // globalFunny->mappingTrie = init_trie(calc_mapping_prefix, calc_statement_prefix);
    int c = 0;
    while (TRUE) {
        c = getc(fp);

        if (c == -1)
            break;

        if (c == COMMENT_CHAR) {
            while (c != '\n')
                c = getc(fp);
            continue;
        }

        if (c == STATEMENT_CHAR) {
            source = get_sys_macro_string(STATEMENT_STR, fp);

            mapping = alloc_mapping();
            mapping->sys = alloc_sys_block();
            mapping->isMacro = FALSE;
            mapping->className = NULL;
            mapping->functionName = NULL;
            mapping->source = source;
            mapping->sourceStatement = parser(source);
            mapping->target = NULL;
            mapping->targetStatement = NULL;
            mapping->starter = to_dfa(mapping->sourceStatement);

            continue;
        } else if (c == NAME_CHAR) {
            mapping->sys->name = get_sys_macro_string(NAME_STR, fp);
            continue;
        } else if (c == FUNCTION_CHAR) {
            mapping->sys->function = get_sys_macro_string(FUNCTION_STR, fp);
            continue;
        } else if (c == MAPPING_CHAR) {
            mapping->sys->mapping = get_sys_macro_string(MAPPING_STR, fp);
            continue;
        } else if (c == RUN_CHAR) {
            mapping->sys->run = get_sys_macro_string(RUN_STR, fp);
            continue;
        } else if (c == EVAL_CHAR) {
            mapping->sys->eval = get_sys_macro_string(EVAL_STR, fp);
            trie_add(globalFunny->mappingTrie, mapping);
            continue;
        } else {
            while (c != '\n')
                c = getc(fp);
            continue;
        }
    }
}


